package cn.edu.zafu.bigdata.x.xiejunjie.networkprogramming;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

public class TimeServer {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888); // 监听8888端口
        byte[] buffer = new byte[1024];
        while (true) {
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet); // 接收客户端的数据包
            String received = new String(packet.getData(), 0, packet.getLength());

            if ("time".equals(received.trim())) { // 检查是否是时间请求
                Date date = new Date();
                String timeString = date.toString();
                byte[] sendData = timeString.getBytes();
                InetAddress address = packet.getAddress();
                int port = packet.getPort();

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);
                socket.send(sendPacket); // 发送当前时间
            }
        }
    }
}
